import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/state/person/persona_entity.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import '../../utils/kudo_helper.dart';
import '../../utils/image_resource_helper.dart';
import '../../utils/time_display_helper.dart';
import '../../widget/report_dialog.dart';
import '../../router/app_navigation_manager.dart';
import '../../widget/login_required_dialog.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_follow_controller.dart';
import '../../state/moment/kite_moment_controller.dart';
import '../../state/moment/kite_moment_entity.dart';
import '../../state/moment/kite_moment_comment_entity.dart';

class KiteMomentDetailScreen extends StatefulWidget {
  final KiteMomentEntity momentData;

  const KiteMomentDetailScreen({super.key, required this.momentData});

  @override
  State<KiteMomentDetailScreen> createState() => _KiteMomentDetailScreenState();
}

class _KiteMomentDetailScreenState extends State<KiteMomentDetailScreen> {
  final TextEditingController _commentInputController = TextEditingController();
  final ReactiveValueNotifier<List<KiteMomentCommentEntity>> _commentsState =
      ReactiveValueNotifier<List<KiteMomentCommentEntity>>([]);

  @override
  void initState() {
    super.initState();
    _loadCommentData();
  }

  @override
  void dispose() {
    _commentInputController.dispose();
    _commentsState.dispose();
    super.dispose();
  }

  void _loadCommentData() {
    final comments = KiteMomentController.globalInstance.getCommentsForMoment(
      widget.momentData.uniqueIdentifier,
    );
    _commentsState.value = comments;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              _buildTopNavigationBar(),
              SingleChildScrollView(
                padding: 80.h.paddingBottom(),
                child: [
                  _buildMediaDisplayContainer(),
                  _buildContentDisplayArea(),
                ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
              ).expanded(),
              _buildBottomCommentInput(),
            ].toColumn(),
      ),
    );
  }

  Widget _buildTopNavigationBar() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 8.h,
        left: 16.w,
        right: 16.w,
        bottom: 12.h,
      ),
      child:
          [
            Icon(
              Icons.arrow_back_ios,
              size: 20.sp,
              color: KudoColors.black,
            ).inkWell(onTap: () => GoRouter.of(context).pop()),
            Text('Kite Culture And Characteristics')
                .fontSize(18.sp)
                .fontFamily(GoogleFonts.lato().fontFamily)
                .fontWeight(FontWeight.w900)
                .textColor(KudoColors.black)
                .expanded(),
            ImageResourceHelper.buildSvgIcon(
              svgPath: 'assets/svg/report.svg',
              width: 22.w,
              height: 22.w,
              color: KudoColors.black,
            ).inkWell(onTap: _showMomentReportDialog),
          ].toRow(),
    );
  }

  Widget _buildMediaDisplayContainer() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: AspectRatio(
        aspectRatio: 343 / 310,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: GestureDetector(
              onTap: _handleMediaContainerTap,
              child: Stack(
                children: [
                  _buildMediaBackground(),
                  if (widget.momentData.isVideoType) _buildVideoPlayIcon(),
                  _buildUserInfoOverlay(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建媒体背景
  Widget _buildMediaBackground() {
    final imageUrl =
        widget.momentData.isVideoType
            ? (widget.momentData.thumbnailResourceUrl ??
                widget.momentData.mediaResourceUrl)
            : widget.momentData.mediaResourceUrl;

    return ImageResourceHelper.buildImageWidget(
      imagePath: imageUrl,
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
  }

  Widget _buildVideoPlayIcon() {
    return Center(
      child: Icon(Icons.play_arrow, color: Colors.white, size: 56.sp),
    );
  }

  Widget _buildUserInfoOverlay() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black.withValues(alpha: 0.7)],
          ),
        ),
        child: _buildUserInfoRow(),
      ),
    );
  }

  Widget _buildUserInfoRow() {
    final authorData = PersonaSessionController.globalInstance.getUserById(
      widget.momentData.authorIdentifier,
    );

    return Row(
      children: [
        Expanded(
          child: Row(
            children: [
              GestureDetector(
                onTap: () {
                  if (authorData != null) {
                    _handleUserAvatarTap(authorData);
                  }
                },
                child: ClipOval(
                  child: ImageResourceHelper.buildImageWidget(
                    imagePath:
                        authorData?.avatarResourceUrl ??
                        'assets/images/avatar1.png',
                    width: 50.w,
                    height: 50.h,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              Text(authorData?.displayAlias ?? 'Unknown User')
                  .fontSize(16.sp)
                  .fontWeight(FontWeight.w900)
                  .fontFamily(GoogleFonts.lato().fontFamily)
                  .textColor(Colors.white),
            ],
          ),
        ),
        SizedBox(width: 12.w),
        _buildFollowButton(),
      ],
    );
  }

  Widget _buildFollowButton() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser == null) {
      return _buildFollowButtonWidget(false, false);
    }

    final isFollowing = PersonaFollowController.globalInstance
        .getFollowStatusState(widget.momentData.authorIdentifier)
        .reactiveValue(context);

    return _buildFollowButtonWidget(true, isFollowing);
  }

  Widget _buildFollowButtonWidget(bool isLoggedIn, bool isFollowing) {
    return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: KudoColors.yellow,
            borderRadius: BorderRadius.circular(11.r),
          ),
          child:
              Text(isFollowing ? 'Followed' : '+Follow')
                  .fontSize(16.sp)
                  .fontWeight(FontWeight.w600)
                  .fontFamily(GoogleFonts.lato().fontFamily)
                  .textColor(KudoColors.black)
                  .italic()
                  .center(),
        )
        .configWidget(borderRadius: 11.r, color: Colors.white)
        .inkWell(onTap: () => _handleFollowButtonTap(isLoggedIn, isFollowing));
  }

  void _handleFollowButtonTap(bool isLoggedIn, bool isFollowing) {
    if (!isLoggedIn) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to follow users',
      );
      return;
    }

    // 检查是否是自己
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser != null &&
        currentUser.uniqueIdentifier == widget.momentData.authorIdentifier) {
      KudoToast.showErrorToast(context, 'You cannot follow yourself');
      return;
    }

    if (isFollowing) {
      PersonaFollowController.globalInstance.unfollowPersona(
        widget.momentData.authorIdentifier,
      );
      KudoToast.showSuccessToast(context, 'Unfollowed successfully');
    } else {
      PersonaFollowController.globalInstance.followPersona(
        widget.momentData.authorIdentifier,
      );
      KudoToast.showSuccessToast(context, 'Followed successfully');
    }
  }

  Widget _buildContentDisplayArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTitleSection(),
          SizedBox(height: 16.h),
          _buildContentsSection(),
          SizedBox(height: 16.h),
          _buildCommentSection(),
        ],
      ),
    );
  }

  Widget _buildTitleSection() {
    return [
      Text('Title')
          .fontSize(20.sp)
          .fontWeight(FontWeight.bold)
          .textColor(KudoColors.black)
          .textAlignment(TextAlign.center)
          .center(),
      Container(
        width: double.infinity,
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          top: 12.h,
          bottom: 12.h,
        ),
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Text(widget.momentData.momentTitle)
            .fontSize(16.sp)
            .fontWeight(FontWeight.w600)
            .fontFamily(GoogleFonts.lato().fontFamily)
            .textColor(KudoColors.black),
      ).configWidget(borderRadius: 20.r).paddingTop(6.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildContentsSection() {
    return [
      Text('Contents')
          .fontSize(20.sp)
          .fontWeight(FontWeight.bold)
          .textColor(KudoColors.black)
          .textAlignment(TextAlign.center)
          .center(),
      Container(
        width: double.infinity,
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          top: 12.h,
          bottom: 12.h,
        ),
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Text(widget.momentData.contentText)
            .fontSize(16.sp)
            .fontWeight(FontWeight.w600)
            .fontFamily(GoogleFonts.lato().fontFamily)
            .textColor(KudoColors.black),
      ).configWidget(borderRadius: 20.r).paddingTop(6.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildCommentSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('Comment')
            .fontSize(20.sp)
            .fontWeight(FontWeight.bold)
            .textColor(KudoColors.black)
            .textAlignment(TextAlign.center)
            .center(),
        Container(
          margin: EdgeInsets.only(top: 12.h),
          child:
              _commentsState.reactiveValue(context).isEmpty
                  ? _buildEmptyCommentState()
                  : _buildCommentList(),
        ),
      ],
    );
  }

  Widget _buildEmptyCommentState() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(24.w),
      decoration: BoxDecoration(
        color: KudoColors.black,
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: Text('No comments yet. Be the first to comment!')
          .fontSize(14.sp)
          .fontWeight(FontWeight.w400)
          .textColor(Colors.white)
          .textAlignment(TextAlign.center),
    ).configWidget(borderRadius: 20.r, color: KudoColors.yellow);
  }

  Widget _buildCommentList() {
    final comments = _commentsState.reactiveValue(context);
    return Column(
      children: comments.map((comment) => _buildCommentItem(comment)).toList(),
    );
  }

  Widget _buildCommentItem(KiteMomentCommentEntity comment) {
    final authorData = PersonaSessionController.globalInstance.getUserById(
      comment.authorIdentifier,
    );

    return Container(
          padding: 12.w.paddingAll(),
          decoration: BoxDecoration(
            color: KudoColors.black,
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: [
            [
              [
                GestureDetector(
                  onTap: () {
                    if (authorData != null) {
                      _handleUserAvatarTap(authorData);
                    }
                  },
                  child: ClipOval(
                    child: ImageResourceHelper.buildImageWidget(
                      imagePath:
                          authorData?.avatarResourceUrl ??
                          'assets/images/avatar1.png',
                      width: 34.w,
                      height: 34.h,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Text(authorData?.displayAlias ?? 'Unknown User')
                    .fontSize(14.sp)
                    .fontWeight(FontWeight.w600)
                    .fontFamily(GoogleFonts.lato().fontFamily)
                    .textColor(Colors.white),
              ].toRowSpace(space: 8.w).expanded(),
              ImageResourceHelper.buildSvgIcon(
                svgPath: 'assets/svg/report.svg',
                width: 22.w,
                height: 22.h,
                color: Colors.white,
              ).inkWell(onTap: () => _showCommentReportDialog(comment)),
            ].toRowSpace(space: 8.w),
            Text(comment.commentContent)
                .fontSize(13.sp)
                .fontWeight(FontWeight.w600)
                .fontFamily(GoogleFonts.lato().fontFamily)
                .textColor(Colors.white)
                .paddingTop(8.h),
            Text(TimeDisplayHelper.formatTimeDisplay(comment.publishTimestamp))
                .fontSize(12.sp)
                .fontWeight(FontWeight.w600)
                .fontFamily(GoogleFonts.lato().fontFamily)
                .textColor(Colors.white)
                .alignRight()
                .paddingTop(4.h),
          ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
        )
        .configWidget(borderRadius: 20.r, color: KudoColors.yellow)
        .paddingBottom(12.h);
  }

  Widget _buildBottomCommentInput() {
    return Container(
      padding: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
        top: 12.h,
        bottom: 30.h,
      ),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Container(
        decoration: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(100.r),
        ),
        child:
            [
              TextField(
                controller: _commentInputController,
                decoration: InputDecoration(
                  hintText: 'Say Something',
                  hintStyle: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey.shade600,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 16.w,
                    vertical: 12.h,
                  ),
                ),
                style: TextStyle(fontSize: 14.sp, color: KudoColors.black),
              ).expanded(),
              Container(
                width: 40.w,
                height: 40.h,
                margin: EdgeInsets.only(right: 4.w),
                decoration: BoxDecoration(
                  color: KudoColors.black,
                  shape: BoxShape.circle,
                ),
                child:
                    ImageResourceHelper.buildSvgIcon(
                      svgPath: 'assets/svg/send.svg',
                      width: 24.w,
                      height: 24.h,
                      color: KudoColors.yellow,
                    ).center(),
              ).inkWell(onTap: _handleSendComment),
            ].toRow(),
      ).configWidget(borderRadius: 100.r),
    );
  }

  void _handleSendComment() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to post comments',
      );
      return;
    }

    final commentText = _commentInputController.text.trim();
    if (commentText.isEmpty) return;

    final success = KiteMomentController.globalInstance.addComment(
      momentId: widget.momentData.uniqueIdentifier,
      authorId: currentUser.uniqueIdentifier,
      content: commentText,
    );

    if (success) {
      _commentInputController.clear();
      _loadCommentData();
      KudoToast.showSuccessToast(context, 'Comment posted successfully');
    } else {
      KudoToast.showErrorToast(context, 'Failed to post comment');
    }
  }

  void _showMomentReportDialog() {
    ReportDialog.show(
      context: context,
      title: 'Report Kite Moment',
      onReport: (reportType) {
        final success = KiteMomentController.globalInstance.deleteKiteMoment(
          widget.momentData.uniqueIdentifier,
        );
        if (success) {
          KudoToast.showSuccessToast(context, 'Reported successfully');
          Navigator.of(context).pop();
        } else {
          KudoToast.showErrorToast(context, 'Failed to report Kite Moment');
        }
      },
    );
  }

  void _showCommentReportDialog(KiteMomentCommentEntity comment) {
    ReportDialog.show(
      context: context,
      title: 'Report Comment',
      onReport: (reportType) {
        final success = KiteMomentController.globalInstance.deleteComment(
          comment.uniqueIdentifier,
        );
        if (success) {
          _loadCommentData();
          KudoToast.showSuccessToast(context, 'Comment reported successfully');
        } else {
          KudoToast.showErrorToast(context, 'Failed to report comment');
        }
      },
    );
  }

  void _handleUserAvatarTap(PersonaEntity user) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser != null &&
        currentUser.uniqueIdentifier == user.uniqueIdentifier) {
      return;
    }

    // 跳转到他人个人页面
    AppNavigationManager.navigateToOtherPersonaScreen(context, user);
  }

  void _handleMediaContainerTap() {
    if (widget.momentData.isVideoType) {
      AppNavigationManager.navigateToKiteVideoPlayer(
        context,
        widget.momentData.mediaResourceUrl,
      );
    }
  }
}
